var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	},
	dataFormat: function (date,format) { //格式化日期
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		
		return format=='date'?(date.getFullYear() + '-' + _format(date.getMonth() + 1) + '-' + _format(date.getDay())): (date.getFullYear() + '-' + _format(date.getMonth() + 1) + '-' + _format(date.getDay()) + ' ' +
			_format(date.getHours()) + ':' + _format(date.getMinutes()));
	},
};

//list适配高度
function listboxheight(height){
	let a = 0;
	 var res = uni.getSystemInfoSync();
	let	windHeight=res.windowHeight;
	let	windWidth=res.windowWidth;
	a = windHeight - height*windWidth/750;
	return a;
}

//请求不带token的
function requestPub(url, postData,methodType, doSuccess, doFail, doComplete,contentType) {
	return uni.request({
	  url: url,
	  data: postData,
	  method: methodType,
	  header: {'content-type': contentType=== undefined?'application/json':contentType},
	  success: function (res) {
		  if (typeof doSuccess == "function") {
			  if(res.data.status!=undefined ){ 
				switch(res.data.status){
				  case 504:
					  uni.showModal({title:"错误提示",content:'网关超时',showCancel:false});
					  break
				  default:
					  uni.showModal({title:"错误提示",content:res.data.error,showCancel:false});
					  break
				} 
			  }
			  else if(res.data.error!=undefined){
				  uni.showModal({title:"错误提示",content:res.data.error_description,showCancel:false});
			  }
			  else{
				  doSuccess(res)
			  }
	      }
	  },
	  fail: function (res) {
	    if (typeof doFail == "function") {
	      doFail()
	    }
	  },
	  complete: function (res) {
	    //uni.hideLoading()
	    if (typeof doComplete == "function") {
	      doComplete()
	    }
	  }
	});
	
}

//请求
function request(url, postData,methodType, doSuccess, doFail, doComplete,contentType) {
	var token = uni.getStorageSync('token')
	// if(token=='' && url.indexOf("/login")<0){
	// 	uni.redirectTo({
	// 		url: '/pages/login/login'
	// 	});
	// 	return;
	// }
	let hide = false ;
	if(methodType.toUpperCase()!='GET'){
	  uni.showLoading({title: '加载中...',mask:true})
	  hide = true ;
	}
	return uni.request({
	  url: url,
	  data: postData,
	  method: methodType,
	  header: {
	    'content-type': contentType=== undefined?'application/json':contentType,
		'Authorization': 'Bearer ' + token
	  },
	  success: function (res) {
		  if (typeof doSuccess == "function") {
			  let code  = res.data.code||'';
				if(code==401){
					uni.navigateTo({
						 url: "/pages/login/login"
					});
				} else {
					doSuccess(res)
				}
	      }
		  if(hide){
			 uni.hideLoading()
		  }
	  },
	  fail: function (res) {
	    if (typeof doFail == "function") {
	      doFail()
	    }
	    if(hide){
		 uni.hideLoading()
	    }
	  },
	  complete: function (res) {
	    if (typeof doComplete == "function") {
	      doComplete()
	    }
	  }
	});
	
}
//选择图片 _this:页面this,canvId:画板id
function chooseimage(_this, canvId) {
  uni.chooseImage({
    count: 1, // 默认9
    sizeType: ['original', 'compressed'],
    sourceType: ['camera'], //sourceType: ['album', 'camera'],
    success: function (res) {
      for (var i = 0; i < res.tempFilePaths.length; i++) {
        drawCanvas(res.tempFilePaths[i], _this.uploadImg, canvId, _this)
      }
    }
  })
}
//画板缩放图片 tempPath:文件路径，uploadImg:上传方法,canvId:画板id,_this:页面this
function drawCanvas(tempPath, uploadImg, canvId, _this) {
  uni.getImageInfo({
    src: tempPath,
    success: function (res) {
      var ctx = uni.createCanvasContext(canvId,_this)
      var ratio = 2
      var canvasWidth = res.width
      var canvasHeight = res.height
      while (canvasWidth > 350) {
        //比例取整
        canvasWidth = Math.trunc(res.width / ratio)
        canvasHeight = Math.trunc(res.height / ratio)
        ratio++
      }
      //设置canvas尺寸
      ctx.drawImage(tempPath, 0, 0, canvasWidth, canvasHeight)

      ctx.setFillStyle('red')
      ctx.setFontSize(10)
      ctx.fillText(dateUtils.getNowFormatDate(), 10, canvasHeight-10)
      ctx.fillText(_this.latitude + '   ' + _this.longitude, 10, canvasHeight - 30)

      ctx.draw(false, function() {
          uni.canvasToTempFilePath({
            canvasId: canvId,
            width: canvasWidth,
            height: canvasHeight,
            success: function(res) {// 上传图片
              if (typeof uploadImg == "function" ) {
                  uploadImg(res.tempFilePath,_this)
              }
            },
						fail:function(e){
							console.log(e);
						}
          },_this)
      })
    }
  })
}
//定位经纬度
function getMyLocation(_seft){
  uni.getLocation({
    type: 'gcj02',
    success: function (res) {
			_seft.latitude=res.latitude;
			_seft.longitude=res.longitude;
    }
  })
}
//获取用户登录code
function getUserCode(doSuccess){
	uni.login({
	  provider: 'weixin',
	  success: function (res) {
		if(res.code) {
			 if (typeof doSuccess == "function") {
			  doSuccess(res.code)
			}
		}
	  }
	});
}
// 下载文件
function downloadFile(url){
	const downloadTask = uni.downloadFile({
			url: url, 
			success: function (res) {
			  // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
			  if (res.statusCode === 200) {
				uni.hideLoading()
				uni.openDocument({
				  filePath: res.tempFilePath,
				  success: function (res) {
					console.log('打开文档成功')
				  }
				})
			  }
			}
	 })
	 downloadTask.onProgressUpdate((res) => {
			uni.showLoading({
			  title: '已下载' + res.progress + '%' // res.totalBytesExpectedToWrite / 1024 / 1024 +'M'
			})
	 })
	  
}

// 回显数据字典, value多个逗号分隔
export function selectDictLabel(datas, value) {
  var actions = []
  Object.keys(datas).map((key) => {
    if (('' + value).indexOf(datas[key].dictValue) > -1) {
      actions.push(datas[key].dictLabel)
      return false
    }
  })
  return actions.join(',')
}
// 时间格式化
export function formatData(data){
	if(!data){
		return data;
	}
    var date = new Date(data.replace(/-/g, '/'));
    var year = date.getFullYear();
    var month = date.getMonth() + 1 + '';
    var day = date.getDate() + '';
	return year+'-'+month.padStart(2, '0')+'-'+day.padStart(2, '0');
}

module.exports = {
	dateUtils: dateUtils,
	request:request,
	requestPub:requestPub,
	getMyLocation:getMyLocation,
	chooseimage:chooseimage,
	downloadFile:downloadFile,
	getUserCode:getUserCode,
	listboxheight:listboxheight,
	selectDictLabel:selectDictLabel,
	formatData: formatData
}
